package category

import (
	"context"
	"encoding/json"
	"go_final/mxshop_api/goods_web/api"
	"go_final/mxshop_api/goods_web/forms"
	"go_final/mxshop_api/goods_web/global"
	goodspb "go_final/mxshop_api/goods_web/proto/protofile"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"google.golang.org/protobuf/types/known/emptypb"
)

func List(c *gin.Context) {
	res, err := global.GoodsClient.GetAllCategorysList(context.Background(), &emptypb.Empty{})
	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	categories := make([]interface{}, 0)
	err = json.Unmarshal([]byte(res.JsonData), &categories)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": "unMarshal json error: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, categories)
}

func Detail(c *gin.Context) {
	categoryID := c.Param("id")
	categoryIDInt, _ := strconv.Atoi(categoryID)

	res, err := global.GoodsClient.GetSubCategory(context.Background(), &goodspb.CategoryListRequest{
		Id: int32(categoryIDInt),
	})
	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, res)
}

func Create(c *gin.Context) {
	categoryForm := forms.Category{}
	err := c.ShouldBind(&categoryForm)
	if err != nil {
		api.HandleValidateError(c, err)
		return
	}

	res, err := global.GoodsClient.CreateCategory(context.Background(), &goodspb.CategoryInfoRequest{
		Name:           categoryForm.Name,
		ParentCategory: categoryForm.ParentCategory,
		Level:          categoryForm.Level,
		IsTab:          categoryForm.IsTab,
	})

	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, res)
}

func Delete(c *gin.Context) {
	categoryID := c.Param("id")
	categoryIDInt, _ := strconv.Atoi(categoryID)

	res, err := global.GoodsClient.DeleteCategory(context.Background(), &goodspb.DeleteCategoryRequest{
		Id: int32(categoryIDInt),
	})

	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, res)
}

func Update(c *gin.Context) {
	categoryID := c.Param("id")
	categoryIDInt, _ := strconv.Atoi(categoryID)

	updateCategoryForm := forms.UpdateCategoryForm{}
	err := c.ShouldBind(&updateCategoryForm)
	if err != nil {
		api.HandleValidateError(c, err)
		return
	}

	request := &goodspb.CategoryInfoRequest{
		Id:   int32(categoryIDInt),
		Name: updateCategoryForm.Name,
	}
	if updateCategoryForm.IsTab != nil {
		request.IsTab = *updateCategoryForm.IsTab
	}

	res, err := global.GoodsClient.UpdateCategory(context.Background(), request)

	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, res)
}
